﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PigArchives
{
    /// <summary>
    /// 获取母耳号
    /// </summary>
    public class SearchMotherHandler : IRequestHandler<SearchMotherCommand, Result>
    {
        /// <summary>
        /// 猪只档案仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> _basicInformationRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchMotherHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="basicInformationRepository"></param>
        /// <param name="logger"></param>
        public SearchMotherHandler(IBaseRepository<BasicInformation> basicInformationRepository, ILogger<SearchMotherHandler> logger)
        {
            _basicInformationRepository = basicInformationRepository;
            _logger = logger;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(SearchMotherCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var query = await (await _basicInformationRepository.GetAll()).Where(x => x.EarNumber == request.EarNumber).FirstOrDefaultAsync();
                if (query != null)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = query;
                    result.Msg = "获取猪只母耳号成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取猪只母耳号异常" + ex.Message;
                _logger.LogError("获取猪只母耳号异常" + ex.Message);
            }
            return result;
        }
    }
}
